package com.epam.cdp.selenium2.core.ui.locators_map;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.epam.cdp.selenium2.core.ui.Screen;
import com.epam.cdp.selenium2.core.ui.locators_map.Elements;

/**
 * @author akhachaturan
 * 
 */
public class ObjectMapReader
{
  private String screenName;

  private String screenPackagePath;

  public ObjectMapReader( Class<? extends Screen> clazz )
  {
    screenName = clazz.getSimpleName();
    screenPackagePath = "src/main/java/" + clazz.getPackage().getName().replace( ".", "/" ) + "/";
  }

  public Map<String, ElementInfoContainer> readElementsMap()
  {
    String packageName = Elements.class.getPackage().getName();
    JAXBContext jc;
    Elements root;
    File objectsMapFile = new File( screenPackagePath + screenName + ".xml" );
    if( !objectsMapFile.exists() )
    {
      throw new RuntimeException( "File with Object Map for screen " + screenName + " was not found." );
    }
    try
    {
      jc = JAXBContext.newInstance( packageName );

      Unmarshaller u = jc.createUnmarshaller();
      root = ( Elements ) u.unmarshal( new File( screenPackagePath + screenName + ".xml" ) );
    }
    catch( JAXBException e )
    {
      throw new RuntimeException( e );
    }
    Map<String, ElementInfoContainer> elementsInfoContainers = new HashMap<String, ElementInfoContainer>();
    List<ElementType> elements = root.getElement();
    for( ElementType element : elements )
    {
      if( element.getXpath() != null )
      {
        elementsInfoContainers.put( element.getName(), new ElementInfoContainer( element.getName(), element.getXpath(),
          null ) );
        continue;
      }
      if( element.getXpattern() != null )
      {
        elementsInfoContainers.put( element.getName(),
          new ElementInfoContainer( element.getName(), null, element.getXpattern() ) );
        continue;
      }
      if( element.getSearchCriterias() != null )
      {
        elementsInfoContainers.put( element.getName(),
          new ElementInfoContainer( element.getName(), element.getSearchCriterias() ) );
      }
    }
    return elementsInfoContainers;
  }
}